package com.adcc.loadsheet.billing.controller;

import com.adcc.aoc.devLib.common.log.Log;
import com.adcc.loadsheet.billing.entity.contractuser.ContractUserEntity;
import com.adcc.loadsheet.billing.entity.export.ExcelItem;
import com.adcc.loadsheet.billing.service.BillingStatisticsService;
import com.adcc.loadsheet.billing.service.ContractUserService;
import com.adcc.loadsheet.billing.util.DateTimeUtil;
import com.adcc.loadsheet.billing.util.LogUtil;
import com.adcc.loadsheet.billing.vo.ResultStatus;
import com.adcc.loadsheet.billing.vo.ResultVO;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 计费统计Controller层
 * Created by zhaoml on 2020/5/18.
 */
@Controller
@RequestMapping(value = "billingstatistics")
@Api(value = "/billingstatistics", description = "计费统计相关操作controller")
public class BillingStatisticsController extends BasisController{

    @Autowired
    BillingStatisticsService billingStatisticsService;

    @Autowired
    ContractUserService contractUserService;

    //进入计费统计页面
    @PreAuthorize("hasPermission('','BillingStatisticsQuery')")
    @GetMapping(value = "tobillingstatisticsquery")
    @ApiOperation(value = "/tobillingstatisticsquery", notes = "跳转到计费统计页面", httpMethod = "GET")
    public String toBillingStatisticsquery(Model model) {
        return "billingStatistics/billingstatistics-query";
    }

    @PostMapping(value = "statistics", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    @ApiOperation(value = "/statistics", notes = "统计", httpMethod = "POST")
    @ResponseBody
    public ResultVO statistics(@RequestBody Map<String, Object> map) {
        ResultVO vo = new ResultVO();
        try {
            // 合同用户关联的普通用户（并授权此功能菜单）可以查询当前合同的用户的舱单计费统计账单，管理员可以查询全部合同用户的计费统计账单
            List<ContractUserEntity> allContractUsers = contractUserService.select(null);
            if(allContractUsers == null || allContractUsers.size() == 0){
                vo.setStatus(ResultStatus.FAILED);
                vo.setErrorReason("没有需要统计的合同用户！");
                return vo;
            }
            //查未指定计费规则的合同用户
            String haveNoBillingRules = contractUserService.selectNoBillingRule();
            if(!Strings.isNullOrEmpty(haveNoBillingRules)){
                //“本合同用户未指定计费阶梯，无法计价！”，不再生成帐单；
                vo.setStatus(ResultStatus.FAILED);
                vo.setErrorReason(haveNoBillingRules.replace(",","合同用户、") + "合同用户未指定计费规则，无法计价！");
                return vo;
            }

            String endMonth = map.get("endMonth").toString();

            /*//统计全部的合同用户，用来判断是否继续统计
            Map<String,Object> statisticsMap = billingStatisticsService.statistics(endMonth,allContractUsers);
            if(statisticsMap.get("errorStr") != null){    //不为空，说明不符合统计条件，给出提示
                vo.setStatus(ResultStatus.FAILED);
                vo.setErrorReason(statisticsMap.get("errorStr").toString());
                return vo;
            }*/

            //取指定合同用户的计费
            ContractUserEntity contractUserEntity = null;
            if(map.get("contractUserId") == null){
                contractUserEntity = allContractUsers.get(0);
            }else {
                Integer contractUserId = Integer.valueOf(map.get("contractUserId").toString());
                contractUserEntity = contractUserService.selectByPrimaryKey(contractUserId);
            }

            //重新传入选中的合同用户进行统计
            List<ContractUserEntity> selectedContractUser = Lists.newArrayList();
            selectedContractUser.add(contractUserEntity);
            Map<String,Object> statisticsMap = billingStatisticsService.statistics(endMonth,selectedContractUser);

            List<ExcelItem> excelItems = (List<ExcelItem>)statisticsMap.get("excelItems");
            if(excelItems != null && excelItems.size() > 0){
                vo.setStatus(ResultStatus.SUCCESS);
                vo.getData().put("excelItems", statisticsMap.get("excelItems"));
                //用以显示合同用户链接，供页面选择
                vo.getData().put("contractUsers", allContractUsers);
                //选中的合同用户，用以页面显示样式判断
                vo.getData().put("contractUserId", contractUserEntity.getContractUserId());
                //标题，页面显示用
                vo.getData().put("title", contractUserEntity.getUserAbbrev() + "集配系统发送数量和费用统计表");
                //年份，页面显示用
                vo.getData().put("year", DateTimeUtil.getYear(endMonth));
            }else {
                vo.setStatus(ResultStatus.FAILED);
                vo.setErrorReason(statisticsMap.get("errorStr").toString());
            }
        }catch (Exception ex) {
            Log.error(BillingStatisticsController.class, "计费统计出错", ex);
            vo.setStatus(ResultStatus.FAILED);
            vo.setErrorReason(String.format(ResultVO.ER_CALL_EX_FAILED, "Query statistics", ex.fillInStackTrace()));
            LogUtil.errorLog(BillingStatisticsController.class, ex, "statistics()");
        }
        return vo;
    }

    //检测导出Excel文件
    @PostMapping(value = "checkexcel", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    @ApiOperation(value = "/checkexcel", notes = "检测导出Excel文件", httpMethod = "POST")
    @ResponseBody
    public ResultVO checkExcel(@RequestBody Map<String, Object> map) {
        ResultVO vo = new ResultVO();
        String endMonth = map.get("endMonth").toString();
        String res = billingStatisticsService.checkExcel(endMonth);
        vo.getData().put("msg",res);
        return vo;
    }

    //导出Excel文件
    @RequestMapping(value = "/excel", method = RequestMethod.GET)
    @ApiOperation(value = "/excel", notes = "导出Excel文件", httpMethod = "GET")
    @ResponseBody
    public void excel(String endMonth,HttpServletResponse response) {
        try{
            billingStatisticsService.excel(endMonth,response);
        }catch (Exception ex) {
            Log.error(BillingStatisticsController.class, "计费统计导出Excel文件出错", ex);
            LogUtil.errorLog(BillingStatisticsController.class, ex, "excel()");
        }
    }
}